package aor2.systembus;

import aor2.common.Tracker;
import aor2.components.Element;
import aor2.components.Restorable;
import aor2.components.records.RecordADbus;
import aor2.cpu.ClockCPU;

public enum ADbus implements Element, Restorable {

	ABus(UNDEFINED), DBus(UNDEFINED);

	long state;

	Tracker history;

	public long getState() {
		return state;
	}

	public void setState(long state) {
		this.state = state;
	}

	private ADbus(long state) {
		this.state = state;
		history = new Tracker();
		history.put(new RecordADbus(this));
	}

	private void clr() {
		state = UNDEFINED;
	}

	public static void clear() {
		ABus.clr();
		DBus.clr();
	}

	public void clearHistory() {

		history = new Tracker();
	}

	public Tracker getHistory() {
		return history;
	}

	public static String info() {
		return "ABus[" + ABus.getState() + "] DBus[" + DBus.getState() + "]";
	}

	@Override
	public void restore(String restorePoint) {
		String trim = restorePoint.replace(beginTag(), "");
		trim = trim.replace(endTag(), "");
		trim = trim.trim();
		String[] states = trim.split(" ");

		ABus.clearHistory();
		DBus.clearHistory();

		ABus.setState(Long.parseLong(states[0], 16));
		DBus.setState(Long.parseLong(states[1], 16));

	}

	@Override
	public String createRestorePoint() {
		return beginTag() + "\n\t" + Long.toHexString(ABus.getState()) + " "
				+ Long.toHexString(DBus.getState()) + "\n" + endTag();
	}

	@Override
	public String beginTag() {
		return "<ADbus>";
	}

	@Override
	public String endTag() {
		return "</ADbus>";
	}

	public void previousClk() {
		RecordADbus tmp = (RecordADbus) history.getFromTop(0);
		if (tmp != null) {
			while (((ClockCPU) (tmp).getMark()).compareTo(ClockCPU
					.getInstance()) > 0 && tmp != null) {
				history.takeFromTop();
				tmp = (RecordADbus) history.getFromTop(0);
			}
			if (tmp != null)
				//setState(((RecordADbus) history.takeFromTop()).getValue());
				state = tmp.getValue();
		}
	}

}
